\documentclass[12pt,twoside,notitlepage]{report}

\usepackage{a4}
\usepackage{verbatim}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{listings}
\usepackage{siunitx}
\usepackage{hyperref}
\usepackage[chapter]{algorithm}
\usepackage{algpseudocode}

\newcommand{\disstitle}{Dynamic Reconfiguration in Mobile Applications}
% POTENTIAL TITLES:
% Automatic Configuration in Mobile Environments
% Automatic Communication Configuration in Mobile Environments
% Data Stream Connection and Message Negotiation
% Flexible Data Streams in Mobile Environments
% Automatic Data Stream Configuration in Mobile Environments
% Automatic Contextual Reconfiguration in Mobile Applications

\newcommand{\wordcount}{11845}

% create extra algorithm commands
\algnewcommand\algorithmiccontinue{\textbf{continue}}
\algnewcommand\Continue{\State\algorithmiccontinue}

\algnewcommand\algorithmicbreak{\textbf{break}}
\algnewcommand\Break{\State\algorithmicbreak}

\hypersetup{
    colorlinks=false,
    pdfborder={0 0 0},
    pdftitle=\disstitle,
    pdfauthor={Tom Smith},
    pdfsubject={Computer Science},
}

% set tab size for lstlisting
\lstset{tabsize=4,basicstyle=\ttfamily}

\lstdefinestyle{xml}{basicstyle=\ttfamily\footnotesize}

\input{epsf}

\raggedbottom                           % try to avoid widows and orphans
\sloppy
\clubpenalty1000%
\widowpenalty1000%

\addtolength{\oddsidemargin}{6mm}       % adjust margins
\addtolength{\evensidemargin}{-8mm}

\renewcommand{\baselinestretch}{1.2}    % adjust line spacing to make
                                        % more readable

\begin{document}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Title


\pagestyle{empty}

\hfill{\LARGE \bf Thomas Smith}

\vspace*{60mm}
\begin{center}
\Huge
{\bf \disstitle} \\
\vspace*{5mm}
Computer Science Tripos Part II \\
\vspace*{5mm}
Sidney Sussex College \\
\vspace*{5mm}
\today  % today's date
\end{center}

\cleardoublepage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Proforma, table of contents and list of figures

\setcounter{page}{1}
\pagenumbering{roman}
\pagestyle{plain}

\chapter*{Proforma}

{\large
\begin{tabular}{l p{9.5cm}}
Name:               & \bf Thomas Smith	\\
College:            & \bf Sidney Sussex College	\\
Project Title:      & \bf \disstitle	\\
Examination:        & \bf Computer Science Tripos Part II, 2013 	\\
Word Count:         & \bf\wordcount\footnotemark[1] \\
Project Originator: & Dr Jatinder Singh		\\
Supervisor:         & Dr Jatinder Singh		\\ 
\end{tabular}
}

\footnotetext[1]{This word count was computed by {\tt detex -e `appendix,figure,algorithm' diss.tex | tr -cd `0-9A-Za-z $\tt\backslash$n' | wc -w}}
\stepcounter{footnote}


\section*{Original Aims of the Project}

The aim of the project was to investigate how applications can respond to changes in context, primarily those arising as a result of mobility. 
This requires some system which allows applications on a mobile device to communicate with peers in different environments. 
When a context change is detected, applications need to be able to discover and connect to relevant peers. 
Finally, applications should be able to make meaningful use of data which is slightly different to their expectations. 
This grants applications the ability to interact with a wider range of peers, allowing greater adaptability to different environments.

\section*{Work Completed}

A messaging middleware was modified to support searching for peers by aspects of their message schema, based on the names and types of fields within that schema, and to allow communication between peers with different message schemas. 
This middleware was ported to Android so that mobile applications could be written which can communicate with any peers using the middleware. 
A mobile application was created which monitors changes in context through various sensors on the device. 
Upon detection of a context change, this application can inform other applications of the change and automatically reconfigure their connections, connecting them to relevant peers. 

\section*{Special Difficulties}

The main difficulty in the project came from porting the messaging middleware to Android. The Android NDK\footnote{\url{http://developer.android.com/tools/sdk/ndk/index.html}} toolkit was used in order to compile the C++ library for use on Android, however missing standard libraries and poor documentation made this task more difficult than expected.
 
%\newpage
\section*{Declaration}

I, Thomas Smith of Sidney Sussex College, being a candidate for Part II of the Computer
Science Tripos, hereby declare that this dissertation and the work described in it are my own work,
unaided except as may be specified below, and that the dissertation
does not contain material that has already been used to any substantial
extent for a comparable purpose. 
I give permission for my dissertation to be made available in the archive area of the Laboratory's website.

\bigskip
\bigskip
\leftline{Signed: }

\bigskip
\bigskip
\leftline{Date: }

\cleardoublepage

\tableofcontents

\listoffigures

\newpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% now for the chapters

\cleardoublepage        % just to make sure before the page numbering is changed

\setcounter{page}{1}
\pagenumbering{arabic}
\pagestyle{headings}

% Intro + Preparation ~ 1400 words
\chapter{Introduction}

% summarise
While many applications exist for mobile devices, few applications themselves are truly mobile. 
The user may happen to be mobile, however applications do not adapt to different environments. 
Applications typically use data from predetermined, often centralised servers, failing to exploit local data which may be available in the environment. 
This project addresses the issues faced in creating applications which can change to suit different environments, demonstrating how applications can perceive an environmental change, how they can find relevant, local data, and how they can achieve some flexibility in the data which they can use. 
This allows applications to be more adaptable to their environment, and therefore offer a more relevant experience to the user. 

\section{Motivation}
% what's the problem

% describe current approach
Current applications tend to be inflexible in where the data they use comes from, often selecting from some predefined set of addresses regardless of the environment. 
While some localisation might be achieved by including parameters during connection, such as sending GPS co-ordinates, the possible parameters which will be accepted have already been fixed, restricting how well applications can adapt to their environment. 
The format of the data, and therefore the content which is being exchanged has also been fixed, restricting applications even further.

This is not in line with the pervasive computing vision \cite{weiser1991computer}, where applications seamlessly interact within an environment, primarily because applications do not use their current environment. 
The systems are not scalable, because applications are using global servers, and they offer no heterogeneity \cite{saha2003pervasive} in the data they use, since both application and server both use an exact format.

Peers which reside in the same environment as an application may be able to provide data which is more relevant to the environment, when compared to a global server, and therefore may be more useful to an application. 
Given an application which requires the current temperature, a global server may use current GPS co-ordinates to determine the nearest weather station and return its most recent reading. 
Yet if the application were being used indoors, a value from a local temperature sensor might not only suffice, but be more appropriate. 
Perhaps this could be achieved otherwise, if the server had known about the temperature sensor, however why should the application need to connect to a global server in order to use local data? Perhaps there isn't even an Internet connection available. 
Furthermore, given that the user is mobile, the server would need to know about {\sl every} temperature sensor {\sl everywhere}. 
Local peers are more related to applications' environments. 
Furthermore, applications need not predefine a list of peers to use.

% context
Context refers to any any happening of interest that can be observed from within a computer which the system or the user feels that it is reasonable to respond to \cite{muhl2006distributed}. 
Mobile devices constantly move between different environments, and these environments determine part of the context which the devices operate in. 
Upon a change in context, an application may move no longer be able to communicate with a given peer, or the data that the peer is providing may no longer be relevant. 
This change in context may require the application to find new peers to interact with, which may be peers providing similar data, or peers providing data more relevant to the new context. 
Each of these peers may offer data which does not meet the application's exact requirements, but can still be useful to the application.  
Some data may be fundamental to the operation of the application, while other parts may be desired, but not crucial. 
Therefore, the application must determine whether each peer offers useful data. 

Even if a peer does offer useful data, the application may still face the difficulty of data being presented in an unexpected format, simply because of the geographical scale and market which the application might be used in. 
Different manufacturers might present data in slightly different formats, or data may be presented in different languages in different countries. 
These factors mean that when comparing similar pieces of data, there may be missing fields, there may be additional fields, or fields may use different names. 
An application may also wish to register a subscription filter with a peer, so that the peer only sends data which the application is interested in. 
However, these filters are specified in terms of the data format, so without knowledge of that data format, the application cannot specify any filters.

% example
\begin{figure}
\input{schema.coach}
\caption[Example Schema for a Coach]{A coach schema, showing a stand number, a date and time of departure, and a list of stops, with town names and estimated arrival times}
\label{fig:coach-schema-intro}
\end{figure}

\begin{figure}
\input{schema.train}
\caption[Example Schema for a Train]{A train schema, showing a structure containing a stand number, a date and time of departure, and a list of stops, with names and estimated arrival times, as well as an additional structure containing a list of items for sale in the on-board shop}
\label{fig:train-schema-intro}
\end{figure}

\begin{figure}
\input{schema.coach.french}
\caption[Example Schema for a French Coach]{A French coach schema, showing the same fields as the English coach schema, however the field names are in French}
\label{fig:french-coach-schema-intro}
\end{figure}

For example, a transport application may face differences in the data format for coaches (Figure \ref{fig:coach-schema-intro}) and for trains (Figure \ref{fig:train-schema-intro}). 
While both offer similar data to a large extent, fields are named differently, and the train schema additionally offers a menu for an on-board shop.
Alternatively, the application might be used abroad, for example in a French coach station. The data will still be very similar, but fields names may be in French (Figure \ref{fig:french-coach-schema-intro}).

An application developer may be able to account for some of these differences, though given the sheer volume of potential peers which the application might communicate with, the developer cannot hope to account for every possibility, meaning that the application cannot be truly adaptable. 
Even if the developer could preempt the interactions with all relevant peers, these peers are liable to change over time. 
New peers may become available and old peers may become unavailable, or peers might change how they present their data. 
A developer simply cannot cover every current and future possibility, meaning an application cannot truly adapt to {\sl any} environment. 
Furthermore, the application might even be used in ways which the original developer had not even imagined, which would not be possible if it could not adapt to unknown peers. 
By specifying how an application should react to changes in context, the application becomes decoupled from the environment, making it more robust to changes in the environment. 

\section{Background}
% what I've done

A context-aware system is defined as one which can examine the computing environment and react to changes in the environment \cite{schilit1994context}. 
This project investigates how automatic contextual reconfiguration can be performed for applications whenever there is a change in the environment. 
Context-awareness can be divided into several categories: contextual sensing, contextual adaptation, contextual resource discovery and contextual augmentation \cite{pascoe1998adding}.
{\sl Contextual sensing} presents environmental state to the user, while {\sl contextual adaptation} allows applications to use this knowledge to adapt their behaviour to integrate with the user's environment.
{\sl Contextual resource discovery} allows applications to discover and exploit resources which exist in the same context as themselves. 
{\sl Contextual augmentation} augments reality with digital data. 
Contextual resource discovery discovers potential peers available within the current context, and contextual adaptation allows applications to adapt to different data formats in order to communicate with these peers. 


% describe context, say only focusing on mobility (Wi-Fi) for now.
Events are often used to represent changes in context \cite{muhl2006distributed,harter2002anatomy,baldauf2007survey,dey2001conceptual}.
Three kinds of events are defined: physical events, timer events, and a state change in the system, all of which may warrant some kind of reconfiguration. 
In a healthcare system, a rapid accelerometer change followed by no movement may represent a physical event (a fall), in which case the application may need to send data to an emergency response team.
A timer event indicates the progression of real time, which advertisers could use to connect to advertisements for nearby restaurants at lunch time. 
Finally, there are state changes in the system, such as a change in network connection or location. 
This project uses all of these types of events to represent a context change. 
Indeed, any event could be used, where an event could be data from any application on the phone, or even elsewhere in the environment. 
Composite events might be considered to represent a context change. 
These emit a single event after the detection of several different events, or one or more occurrences of a single event \cite{chakravarthy1994composite}. 

\section{Project Goals}
% pervasive computing

The project aims to create a context-aware middleware which is in line with the goals of the pervasive computing vision \cite{weiser1991computer}. 
The approach taken offers heterogeneity, which allows it to be used {\sl anywhere}, and offers mobility and scalability, which allows it to be used {\sl everywhere}. 
These factors are important because uniformity and compatibility in every environment cannot be assumed. 

\begin{itemize}

% mobility
\item
The project modifies a middleware for use on mobile devices, allowing developers to write applications which can be used in different environments. 
Mobile computing is fundamentally about increasing our capability to physically move computing services with us \cite{lyytinen2002ubiquitous}, and thus mobility forms a particularly important part of context because people move between different environments. 

% context, reconfiguration
\item
The project offers dynamic connection reconfiguration for applications, discovering peers within the environment which are relevant to them, and connecting applications to these peers upon a context change. 
This reconfiguration is invisible to the user, occurring automatically following a context change. 
Connections to peers are established on an ad-hoc basis and based entirely upon which peers are available within the environment at that time. 
The approach is scalable because applications are not bound to particular peers, thus can cope with a dynamically changing set of peers. 

% schema stuff
\item
The project allows applications to communicate with peers despite differences in their data formats. 
This adaptation to different data formats masks any heterogeneity in the data \cite{saha2003pervasive} from both users and the application developers. 
This further ensures that the approach is scalable, because applications are not bound to a particular data format. 

\end{itemize}


\section{Project Overview}

% policy engine
The project provides a way for applications control how their connections should be reconfigured through policies. 
An application monitors the environment and upon detecting a change in context applies these policies, reconfiguring applications' connections to connect them to different peers, where appropriate.
These policies may specify the name of peers to connect to, or be more complex rules regarding the structure of peers' data. 
Additionally, policies specify the conditions in which they should be applied. 
Applications may also opt to be notified of a change in context, allowing them to perform callback methods upon the context change.

% repackaging
Depending on its policy, an application may be connected to a peer which provides data in a format which differs from its own.
This can be handled by reformatting the data to match the expected format. 
Any extraneous fields are removed, any absent fields are filled with ``empty'' values, and the policy is used to infer relationships between fields with different names. 
This converted data can then be passed to the application, allowing the application to continue as if the data received had conformed to its own data format. 
% subscription
Additionally, any subscription filter which an application has placed on data it should receive, in terms of its own data format, are converted to match the peer's data format, so that the application can be connected with a working subscription in place. 


% summarise
Applications' connections can be automatically reconfigured upon a change in context, and data is automatically repackaged to comply with the format which an application expects. 
Local peers can provide data relevant to the environment, and this data can be converted to fit each application's expected format, so that applications are no longer bound to exact data formats. 
This grants applications flexibility in the peers which they connect to, making them more adaptable to the environment. 
Applications control how they interact with an environment through policies, while still seamlessly communicating within that environment.

\cleardoublepage

 
\chapter{Preparation}

This chapter first outlines the requirements of a context-aware system. 
It goes on to summarise related work which the project builds on, namely the SBUS middleware \cite{ingram2009reconfigurable}, as well as other work which might have been used. 
Finally, it describes how a system has been designed to meet these requirements.

%TODO: Why the recursive discovery through peer inspection hasn't been implemented, and how it could be (should be somewhere else?)

\section{Requirements Analysis}

The following use cases outline the functional requirements of the system, describing how the system should operate in different circumstances.

% use cases - functional requirements
John uses a National Heritage application which can provide information about exhibits in a museum, or nearby landmarks in a city. 
While in a museum, John's phone is connected to the Wi-Fi network, and the application receives data from a source on the network, which provides a guided tour of the museum. 

\begin{itemize}

\item {\bf Detect and Act upon Change in Context}

\begin{enumerate}

\item John uses the application to view information about each exhibit while walking around the museum.

\item Upon leaving the museum, his phone disconnects from the Wi-Fi network.

\item From this change in the network, the system detects that John has left, so connects the application to a global source via 3G, which uses his GPS co-ordinates to provide the application with information about nearby landmarks, so that John can decide where to go next. 

\end{enumerate}

\item {\bf Connect to Relevant Peers}

\begin{enumerate}

\item John chooses to visit a nearby art gallery, and upon entering the gallery connects his phone to the Wi-Fi network.

\item The system detects this change, and searches for sources providing ``museum data''.

\item Once the system finds a source, it connects the application to the source, filtering data based on John's location, so that he only receives data relevant to the exhibit which he is viewing.  

\end{enumerate}

\item {\bf Allow Communication Between Incompatible Schemas}

\begin{enumerate}

\item The art gallery is trialling a new system which includes data for items available in the gift shop which are relevant to each exhibit. 

\item John's application does not support this extra field, making the source incompatible with the application.

\item The system converts these art gallery messages to match the application data format, making the data compatible with John's application. 

\end{enumerate}

\end{itemize}

%TODO: more of this.
% non-functional requirements
Due to the unpredictable nature of mobile environments, the system must also meet certain non-functional requirements to ensure that is is responsive and usable. 
The system must search for peers to connect to within a reasonable time, and any message conversion required for a given peer must incur negligible delay.
These constraints are necessary so that any communication between peers remains relevant to the user's context.

\section{SBUS}

SBUS \cite{ingram2009reconfigurable} is a messaging middleware written in C++, which supports both stream based and client-server communication. 
The basic entity in SBUS is a {\sl component}. 
Each component consists of one or more {\sl endpoints} which can be connected, or {\sl mapped} together allowing direct communication between the two endpoints. 
Every endpoint has an associated message schema, which dictates the format that its data must adhere to. 
In order for endpoints to be mapped together, their schemas must match. 
An endpoint may specify a subscription filter on events it wishes to receive, in terms of its schema. 
This filter specifies conditions on the events which an endpoint is interested in, and any connected peers will only publish events to this endpoint if the event matches the conditions.

These connections and subscriptions are dynamically reconfigurable and thus may be modified by any other component at run time, subject to security policies. 
This allows third party remapping to occur, where a component may issue a message to some other component, instructing it to map or unmap its endpoints, or to update its subscription filters. 

\begin{table}
\centering

\begin{tabular}{l l l}
\hline\hline
Code	&	Parameter 	& Example Query\\
\hline

{\tt +N}	&	Component Name	& +Ntemperature \\
{\tt +I}	&	Instance Name	& +Igreenhouse \\
{\tt +X}	&	Public Key		& +Xkey \\
{\tt +K}	&	Keywords		& +Kecosystem \\
{\tt +P}	&	Peers 			& +Phumitidy \\

\hline
\hline
\end{tabular}

\caption{RDC Query Types}
\label{tab:rdc_queries}
\end{table}

Resource discovery components (RDCs) are components which act as a component discovery service. 
An environment may contain several RDCs, or no RDCs, though typically one RDC exists in each environment.
Components may query an RDC for other components within the environment, using the parameters shown in Table \ref{tab:rdc_queries}.
These constraints are specified using a query string, and a component must match all constraints in a query. 
The RDC returns the IP addresses of matching components, allowing the component to establish a direct connection to a match.

\section{Related Work}

% other ways to do context
AWARE\footnote{\url{http://www.awareframework.com/home/}} is a new Android framework which can notify applications of the current context by broadcasting {\sl intents}, which can be can be captured by Android BroadcastReceivers\footnote{\url{http://developer.android.com/reference/android/content/BroadcastReceiver.html}}. 
This allows any application to implement a broadcast receiver to be notified of changes in context, and to perform a callback method upon a change. 
This could be used to detect context changes, although has not yet been released. 

% messaging middlewares
Several other messaging middlewares exist, such as the Java Message Service (JMS) \cite{hapner2002java}, or the Advanced Message Queuing Protocol (AMQP) \cite{vinoski2006advanced}.
JMS provides an API for sending and receiving messages in Java, and thus the obvious flaw is that it only supports programs written in Java, which does not fit the heterogeneous needs of pervasive computing. 
AMQP attempts to solve this problem by creating a standard to ensure interoperability between different implementations. 
Several implementations exist for Java, such as ActiveMQ or RabbitMQ. 
However, AMQP uses a central broker for peers to communicate, thus cannot scale as well as a decentralised messaging system. 

The key aspect missing from both of these is the ability to perform third party reconfiguration. 
This is fundamental to the project, because applications manage connections on behalf of others, performing reconfiguration according to application policies, rather than requiring each application to enforce its own policies. 
SBUS allows this reconfiguration to take place. 

SBUS components can be written in C++, allowing them to run on most machines, and through the Android port can now be written in Java. 
Components communicate directly, which allows scalability, and are independent of the device or platform they are running on. 
Communication is not only independent of the device and platform, but also the network connectivity. 
Components communicate using TCP, which means that the middleware will work over Wi-Fi, 3G, Bluetooth, and any compatible network infrastructure. 

\section{Project Outline}

This project extends the SBUS middleware to enable it to function on mobile devices, and to support the exchange of heterogeneous data between peers where necessary. 
Applications implement an SBUS component, sending and receiving messages on endpoints. 

% Android NDK
The Android Native Development Kit\footnote{\url{http://developer.android.com/tools/sdk/ndk/index.html}} (NDK) can be used to embed the native machine code into applications, and was used to compile SBUS libraries for the Android platform. 
Since the NDK offers fairly obscure documentation with little more than trivial examples, some time was required to understand how the build process works. 
The Java Native Interface (JNI) framework allows Java applications to call functions implemented in native libraries \cite{liang1999java}. 
Using the Android NDK and JNI framework, functions in the SBUS library can be called from Android applications implemented in Java, which are running in a virtual machine. 

% How applications will find peers relevant to them (constraints in terms of schema)
When components query the RDC they generally know something about the metadata of components they want, such as names, connected peers, or public keys. 
In a mobile environment, this is unlikely to be the case. 
Given the amount of possible environments, and the amount of different companies operating in these environments, an application cannot rely on static information about the components. 
The components may, and are perhaps even likely to change over time, meaning that a more robust solution is required. 
To allow applications to find relevant components in any environment, SBUS has been extended to allow RDC queries centred around data. 
The ability to search for components by the format of their data allows components to discover other components which provide data they require, without any prior knowledge of the environment. 
This is well suited to mobile applications because the environment is constantly changing. 
Furthermore, these environments are not all controlled by a single company and this solution allows resource discovery independent of any corporate differences. 

% How applications will cope with unexpected data format - must be done at system level
SBUS endpoints could previously only communicate if they shared a common message schema, or if one was a {\sl polymorphic} endpoint, which could accept any message. 
These polymorphic endpoints are not used in the project, because although they can use messages matching any schema, these messages may be different every time, and thus do not offer a consistent message structure which can be used by an application. 
Generally endpoints only ever receive messages matching their own schema, from which values can be easily extracted since the structure of the message is known. 
Different components in different environments may offer similar data, but they may have schema differences, perhaps due to the company providing the component, or the country which the component is located in. 
When searching for components by data, an application may discover some component which provides the required data, but nested within a larger schema, or using different field names. 
In the previous SBUS implementation, the application would not be able to communicate with this component. 
% TODO: example
Even if it were able to, the application would not know the structure of the message, so cannot locate a particular value within it without performing some complex parsing. 
This is obviously undesirable since {\sl every} application would have to implement a parser which could handle peers in {\sl every} environment, all of which might use slightly different schemas.
To avoid each application implementing such a parser, these differences are now handled by SBUS, before the application receives the message. 
SBUS has been extended to allow components to communicate despite schema differences by reformatting any incoming message to match the application schema. 
This moves the parsing to the middleware level, which both removes the burden of implementing a parser from the developers of individual applications, and guarantees that all applications can be used with different peers, because they do not need to rely on the developer implementing a parser. 
This means that an application will only receive messages matching its schema, never facing any uncertainty in the structure of a message. 

% How change in context will be detected
A typical smartphone offers a growing set of sensors \cite{lane2010survey} which can be used to determine a context change. 
Android applications can register to receive intents\footnote{\url{http://developer.android.com/reference/android/content/Intent.html}} which indicate events such as a network change, or an incoming phone call. 
Furthermore, the AIRS application\footnote{\url{https://play.google.com/store/apps/details?id=com.airs}} monitors sensors on the phone, and can output sensor readings to a remote server.
The system uses these intents, and act as a server for AIRS to obtain these sensor readings, allowing it to monitor the environment, and determine context changes. 
Upon detecting a context change, it can then remap other applications on the phone, connecting them to peers suited to the environmental context. 

% How applications' connections will be reconfigured (spoke map)
In order for the system to remap applications, it first needs to know about them. 
An RDC is well suited for this, because it maintains a list of registered components, which can then be searched when a component queries the RDC. 
This list can also serve as a list of components which the system can remap.

These two aspects of detecting context change and acting as an RDC have been combined into a Phone Manager application. 
The Phone Manager acts similarly to an RDC, allowing applications on the device to register with it. 
It detects context changes, and upon a change issues messages to registered components to instruct them to remap to other components.

% How the Phone Manager knows what to reconfigure to (policies)
The Phone Manager remaps applications upon a change in context, but must remap them to appropriate places. 
The Phone Manager cannot decide what constitutes ``appropriate'' for any given application, as such, the application must decide for itself. 
Applications can register {\sl policies} with the Phone Manager which dictate how they should be remapped upon context changes. 
These policies specify the type of context change they apply to, any conditions which that context change must satisfy, and how the application should be remapped. 
This may be an IP address to map to, or a query which can be performed against an RDC in the environment, which will then return matching components. 
The Phone Manager simply remaps applications as specified by their policies.

% Security
Security, while an important concern, is not the focus of this project. 
A version of SBUS which uses encrypted connections, and has authentication and authorisation mechanisms has been developed in parallel with the project. 
These two branches have been integrated, so that all of the work undertaken in this project could be applied to that version of SBUS.

\cleardoublepage


% ~ 4000 words
\chapter{Implementation}

This chapter first shows how applications can find peers which offer the data they require, and then demonstrates how they can communicate with these peers despite differences in schemas. 
It goes on to explain how the SBUS library was ported to Android to allow mobility, and how application developers can use SBUS. 
It then describes how the Phone Manager is responsible for detecting changes in context and reconfiguring applications' connections upon a change, and how integration with AIRS exposes sensors on the phone to provide a way to monitor context. 
Finally, some remaining issues and potential solutions are examined, which have not yet been implemented due to time constraints. 

\section{Schema Matching}

Schema matching refers to components matching peers based on aspects of their schema, specifically whether or not their schema contains certain fields, and how components can communicate with these peers if their schemas are not identical. 

% syntax
The most natural way for a component to query an RDC with data constraints seemed to be to extend the current query mechanism. 
When searching, a component may be interested in an exact match, where both field names and types match, or a weaker match where only field types must match. 
Since a component only knows about its own schema in advance, these queries must be specified in terms of its own schema.
Two new query parameters have been introduced to allow this functionality. 
An exact match is specified by {\tt +H}, representing a schema {\sl has} an item, and a type match is specified by {\tt +S}, representing a schema has a {\sl similar} item.
Each of these is used with the name of a single item in the component's schema.
If this item is a single field, it refers only to that field, whereas if it is a composite item consisting of multiple fields, the query applies recursively to the entire item. 
Any item which does not exist in the schema is ignored. 
Table \ref{tab:example_schema_syntax} demonstrates some possible queries based on the schema in Figure \ref{fig:locationschema}.

\begin{figure}
\begin{lstlisting}
@location
{
	gps
	{
		dbl longitude
		dbl latitude
		int altitude
	}
	txt city
}
\end{lstlisting}
\caption{Location Schema}
\label{fig:locationschema}
\end{figure}

\begin{table}
\centering

\begin{tabular}{l l}
\hline\hline
Query & Match \\
\hline

{\tt +Scity}		& {\tt city} field type ({\tt txt}) \\
{\tt +Hlongitude}	& {\tt longitude} field exactly \\

{\tt +Sgps}			& {\tt gps} item type \\
{\tt +Hgps}			& {\tt gps} item exactly \\

{\tt +Hcountry}		& {\tt <ignored>} \\
{\tt +Hlocation}	& {\tt location} schema exactly \\

{\tt +Sgps+Hlongitude}	& {\tt gps} item type AND {\tt longitude} field exactly \\

\hline
\end{tabular}

\caption{Example Schema Syntax}
\label{tab:example_schema_syntax}
\end{table}

% nested syntax
The final entry in Table \ref{tab:example_schema_syntax}, {\tt +Sgps+Hlongitude} bears an interesting case. 
This currently specifies that a schema must contain an item matching the type of {\tt gps} and must also contain the field {\tt longitude} {\sl anywhere} in the schema. 
An alternative use might be considered where the user wishes to specify that the schema must contain a item matching the type of {\tt gps}, and must also contain the field {\tt longitude} {\sl within that item}. 
This allows a query to be specified that would match a item which renames {\tt altitude} as {\tt height}, but not one which renames {\tt longitude} as {\tt long}. 
The latter could still be matched in the current case, if the {\tt longitude} field existed elsewhere in that schema. 

This usage is implemented through a nested syntax, where constraints can have child constraints attached. 
Again, any items which do not exist in the schema are simply ignored. 
Table \ref{tab:nested_schema_syntax} demonstrates some possible nested queries based on the schema in Figure \ref{fig:locationschema}. 
Clearly in the last two cases, the nested constraint is irrelevant, because they offer no stronger match criteria than their parent. 
In this situation, the nested constraint is simply ignored.

\begin{table}
\centering

\begin{tabular}{l p{8cm}}
\hline\hline
Query & Match \\
\hline

{\tt +Sgps}							& {\tt gps} item type \\
{\tt +Sgps[+Hlongitude]}			& {\tt gps} item type containing {\tt longitude} field exactly \\
{\tt +Sgps[+Hlongitude+Hlatitude]}	& {\tt gps} item type containing {\tt longitude} and {\tt latitude} fields exactly \\

{\tt +Sgps[+Hcountry]}				& {\tt gps} item type \\

{\tt +Sgps[+Hlongitude]+Hcity}		& ({\tt gps} item type containing {\tt longitude} field exactly) AND {\tt city} field exactly \\

{\tt +Sgps[+Slongitude]}			& {\tt gps} item type \\
{\tt +Hgps[+Slongitude]}			& {\tt gps} item exactly \\

\hline
\end{tabular}

\caption{Nested Schema Syntax}
\label{tab:nested_schema_syntax}
\end{table}

\begin{algorithm}
\begin{algorithmic}[1]
\While{$token \neq null$}
	\If{token is a constraint}
		\State $\Call{list.add}{constraint}$
		\State $list.last \gets constraint$
	\Else
		\If{token is open bracket}
			\State $\Call{stack.push}{list}$
			\State $list \gets list.last.children$
		\ElsIf{token is close bracket}
			\State $list \gets \Call{stack.pop}$
		\EndIf
	\EndIf
\EndWhile
\end{algorithmic}
\caption{Parse Nested Constraints Using a Stack}
\label{alg:parse_nested}
\end{algorithm} 

% how the parser build up the nested structure of constraints to match
The existing parser for RDC queries was extended to allow these new constraint types. 
Upon encountering a {\sl has} or {\sl similar} constraint, the field name, type of match and pointer to a list of children are added to a list. 
Algorithm \ref{alg:parse_nested} shows how a stack is used to handle nested constraints \cite{appel1998modern}. 
An opening bracket causes the list of constraints to be pushed to the stack.
Subsequent constraints are then added to the child constraints of the last item in that list. 
A closing bracket pops the list off the stack, and constraints are appended to this list again. 
Some error checks also exist to ensure that additional opening brackets are ignored if the list is empty, since they have no meaning, and that closing brackets are ignored if there are too many, since there may not be a list on the stack. 
For example, the checks would reduce {\tt [+Sgps[[+Hlongitude]]]]} to {\tt +Sgps[+Hlongitude]}.
Figure \ref{fig:nested_query} shows how the query {\tt +Sgps[+Hlongitude]} would be represented.

% nested query representation
\begin{figure}
\begin{lstlisting}[style=xml]
<constraint>
	<name>"gps"</name>
	<exact>false</exact>
	<children>
		<constraint>
			<name>"longitude"</name>
			<exact>true</exact>
			<children></children>
		</constraint>
	</children>
</constraint>
\end{lstlisting}
\caption{Nested Query Representation}
\label{fig:nested_query}
\end{figure} 

% hashes - overview
Each SBUS endpoint currently has an associated {\sl message hash} of the canonical representation of its schema, which can be used to efficiently compare its schema to another schema. 
This hash is computed when the endpoint is created, and determines whether endpoints are able to communicate. 
To create the hash, the schema is read by a top-down parser, which generates tokens representing different items in the schema. 
This parser operates recursively on composite items within the schema, and each token is added to a single buffer. 
Once the parser returns, this buffer contains a canonical representation of the schema, from which a hash can be computed. 

% hashes for subschemas.
These hashes can be used to efficiently compare entire schemas, and indeed this takes place when two endpoints attempt to connect. 
However, to compare {\sl parts} of a schema, the schema must be represented not by a single hash, but by a collection of hashes. 
This collection of hashes can also be built when parsing the schema. 
When parsing each individual item, where an item is either a single field or a composite item consisting of multiple fields, a new buffer is used. 
Before the parser returns, a hash is computed of the item contained in that buffer. 
Furthermore, an exact hash is computed using both the names and types, and a type hash is computed using only types. 
This is achieved by using two buffers, with no names being appended to one of them. 
These hashes can then be added to the collection, and the contents of the buffers appended to the parent buffers. 
Using this method, a collection of hashes is built containing the hash of each item within the overall schema. 

\begin{figure}
\begin{lstlisting}[style=xml]
<location has="9791265A42AB" similar="882A3A2DA208">
	<gps has="55E21713DEAA" similar="931DEF188280">
		<longitude has="BE25D0A889CA" similar="00000019316C" />
		<latitude has="87AC6D018868" similar="00000019316C" />
		<altitude has="B3ACB8255B56" similar="0000001A7774" />
	</gps>
	<city has="D3C74C7A7AB4" similar="0000001D3C74" />
</location>
\end{lstlisting}
\caption{Hash Structure Generated For Location Schema}
\label{fig:locationhashes}
\end{figure}


This collection is in fact built using lists, where each composite item contains both its hashes and a pointer to a list of its children's hashes.
This representation retains the overall structure of the schema, which will be used for nested searches. 
Figure \ref{fig:locationhashes} shows an XML representation of the hash collection which is generated for the schema in Figure \ref{fig:locationschema}.


% how to query RDC.
To construct a schema query for the RDC, each item in the constraint list is looked up in the hash collection and the appropriate hash is added to the item, depending on whether the item states an exact or type match. 
Figure \ref{fig:nested_query_hash} shows the query in Figure \ref{fig:nested_query} with these hashes. 
This list can then be sent to the RDC, which uses it to search for matching components. 

% nested query hashes representation
\begin{figure}
\begin{lstlisting}[style=xml]
<constraint>
	<name>"gps"</name>
	<exact>false</exact>
	<hash>"931DEF188280"</hash>
	<children>
		<constraint>
			<name>"longitude"</name>
			<exact>true</exact>
			<hash>"BE25D0A889CA"</hash>
			<children></children>
		</constraint>
	</children>
</constraint>
\end{lstlisting}
\caption{Nested Query Representation with Hashes}
\label{fig:nested_query_hash}
\end{figure}

% how RDC searches.
The RDC has the schema of each endpoint on each registered component, therefore has the hash collection of each endpoint. 
This hash collection is only computed once. 
The RDC returns all matching endpoints, not just the first match, so compares the query with each endpoint schema. 

\begin{algorithm}
\algnotext{EndIf}
\begin{algorithmic}[1]
\Function{CompareSchema}{$constraints$, $schema$}
	\ForAll{$constraint \in constraints$}
		\If{$constraint.hash = schema.hash(constraint.exact)$}
			\If{$constraint.exact$} \label{alg:line:constraint_exact}
				\Continue \Comment match, check next constraint
			\ElsIf{$constraint.children = null$}
				\Continue \Comment match, check next constraint
			\Else \label{alg:line:nested_start}
				\ForAll{$nested \in constraint.children$}
					\State $match\gets false$
					\ForAll{$child \in schema.children$}
						\State $match\gets \Call{CompareSchema}{nested, child}$
						\If{$match$}
							\Continue \Comment match, check next nested constraint
						\EndIf
					\EndFor
					\If{$match \neq true$}
						\Break \Comment no match, skip other nested constraints
					\EndIf
				\EndFor
				\If{$match$}
					\Continue \Comment match, check next constraint
				\EndIf
			\EndIf \label{alg:line:nested_end}
		\Else
			\State $match\gets false$
			\ForAll{$child \in schema.children$}
				\State $match\gets \Call{CompareSchema}{constraint, child}$
				\If{$match$}
					\Continue \Comment match, check next constraint
				\EndIf
			\EndFor
			\If{$match \neq true$}
				\State \Return $false$
			\EndIf
		\EndIf
	\EndFor
	\State \Return $true$
\EndFunction 
\end{algorithmic}
\caption{Pseudocode to Compare Schemas}
\label{alg:compare_schema}
\end{algorithm}

Algorithm \ref{alg:compare_schema} shows how the RDC checks whether a schema satisfies a set of constraints. 
Ignoring lines \ref{alg:line:nested_start}--\ref{alg:line:nested_end}, which check child constraints, the algorithm is simply a depth-first search \cite{tarjan1972depth}. 
Each constraint is checked against the schema. 
If the constraint hash matches the appropriate schema hash, then the next constraint is checked, or the algorithm returns {\tt true} if there are no more constraints. 
If the hashes do not match, then the algorithm recursively calls itself using each of the schema's children as the new schema to compare against, until a match is found. 
If no match is found, then the algorithm returns {\tt false}. 
Lines \ref{alg:line:nested_start}--\ref{alg:line:nested_end} match nested constraints very similarly to the entire algorithm as described above. 
However, because these constraints specify fields which must be nested, then cannot be compared to the current item being matched. 
Therefore, the comparison must be conducted against each of the schema's children. 
Once a match is found the next constraint is tested, and if all nested constraints are matched, then the parent constraint is considered matched. 
Line \ref{alg:line:constraint_exact} checks whether a constraint is exact before its children are considered, since if it is an exact match, the children must match by definition. 

% optimisations to search
Queries are automatically optimised by components before being sent to the RDC, to increase performance of the algorithm. 
Any duplicate constraints are first removed, for obvious reasons. 
Queries are then reordered to place either exact constraints first, constraints on composite items first, or a combination of these. 
This orders constraints such that those which are more difficult to match are checked first, causing the algorithm to fail earlier rather than later, thereby wasting less time. 
This allows the RDC to process the query as quickly as possible, preventing it from becoming a bottleneck in the system. 
The result of these optimisations is explored in the Evaluation. 

%TODO: other ways the search could be optimised - hash table to linked lists, search tree. Potential performance increases + how results might vary.

\section{Schema Conversion}

Schema conversion is used to allow two components with different message schemas to communicate coherently. 
It takes place during connection setup between components, which may be connecting to a match returned by an RDC following a schema constraint query, or connecting to a component at a known address while specifying schema constraints. 
The conversion is performed almost entirely by the component initiating the connection, so as not to hinder the target peer. 

% construct lookup
The component first requests the target's schema. 
Upon receiving this schema, the component builds a table of corresponding field names using the schema constraints, which also ensures that the schema does in fact match the constraints. 
Corresponding field names between the two schemas are stored in two tables, one indexed using field names from the target schema, the other indexed using field names from the component schema. 
This lookup table is used to repackage messages according to this component's schema. 

\begin{figure}
\begin{lstlisting}
@place
{
	coordinates
	{
		position
		{
			dbl longitude
			dbl latitude
			int height
		}
	}
	txt country
}
\end{lstlisting}
\caption{Complex Location Schema}
\label{fig:complexlocationschema}
\end{figure}

\begin{table}[b]
\centering

\begin{tabular}{c c}
\hline\hline
Current & Target \\
\hline
{\tt longitude} & {\tt longitude} \\
{\tt gps} & {\tt position} \\
{\tt latitude} & {\tt latitude} \\
{\tt altitude} & {\tt height} \\

\hline
\end{tabular}

\caption{Corresponding Field Names}
\label{tab:lookup_table}
\end{table}
 
Entries are added to these tables every time a successful match occurs in Algorithm \ref{alg:compare_schema}. 
Additionally, entries can be inserted for all descendants of a successful match, since the structure of the schemas must be the same. 
Table \ref{tab:lookup_table} shows the corresponding field names which would be added to the tables when an endpoint using the schema in Figure \ref{fig:locationschema} connects to an endpoint using the schema in Figure \ref{fig:complexlocationschema} with the query {\tt +Sgps[+Hlongitude]}.

Once this basic lookup table has been created, corresponding fields within the two schemas can be located, which allows a correspondence between outer structures to be inferred, as shown in Algorithm \ref{alg:construct_lookup_outer}. 
The first loop works upwards from a corresponding field in the schema and target schema. 
Given that these fields match, their ancestors must also match. 
This loop will end once one of the schemas has no parent, adding ({\tt location}, {\tt coordinates}) to the lookup table in this case. 
Only one schema will have remaining ancestors, however if the top level of both schemas has been reached, no further action is taken. 
If the target schema has remaining ancestors, these represent layers which surround the message the component will use. 
These are stored so that a message can be extracted from within these layers. 
Here, {\tt place} is the only extra layer and {\tt place/coordinates} is the root of the message the component wants. 
If the component schema has remaining ancestors, these represent layers which are missing from the message. 
These are stored so that the message can be wrapped in them. 

\begin{algorithm}
\algnewcommand\And{\textbf{ and }}
\algnotext{EndWhile}
\begin{algorithmic}[1]
\While{$current \neq null \And target \neq null$}
	\State \Call{InsertLookup}{$current.name$, $target.name$}
	\State $current\gets current.parent$
	\State $target\gets target.parent$
\EndWhile
\While{$target \neq null$}
	\State \Call{AddExtra}{$target$}
	\State $target\gets target.parent$
\EndWhile
\While{$current \neq null$}
	\State \Call{AddMissing}{$current$}
	\State $current\gets current.parent$
\EndWhile
\end{algorithmic}
\caption{Lookup Table Inference for Outer Structures}
\label{alg:construct_lookup_outer}
\end{algorithm} 

% updating subscriptions
After the lookup table has been created, any predefined subscription filter can be applied to the peer. 
These filters are specified in terms of field names, for example the filter {\tt location/gps/latitude > 0.0} specifies the northern hemisphere. 
If the component schema has additional ancestors, then these are removed from the filter, while if the target schema has additional ancestors, the filter is prefixed with these, replacing the top level node to make the filter {\tt place/coordinates/gps/latitude > 0.0}.
Other field names are then replaced with their corresponding entry in the lookup table, creating a filter which when applied to the target schema, has the expected effect, namely {\tt place/coordinates/position/latitude > 0.0}.
Any filters on fields which do not exist in the target schema are applied as specified, so developers must ensure that fields which they intend to filter on are included within their schema query. 
This converted filter will be applied in the final stage of the connection setup, and of course can be updated at any later time. 

\begin{algorithm}
\begin{algorithmic}[1]
\Function{Repack}{$message$}
	\If{message has additional layers}
		\State \Call{UnwrapMessage}{$message$}
	\EndIf
	
	\State \Call{RepackageMessage}{$message$}
	
	\If{message is missing layers}
		\State \Call{WrapMessage}{$message$}
	\EndIf
\EndFunction 
\end{algorithmic}
\caption{Pseudocode to Repackage Message}
\label{alg:repack_message_overall}
\end{algorithm}

Finally, this lookup table will be used to repackage each message. 
Algorithm \ref{alg:repack_message_overall} shows how each message is repackaged. 
Suppose the component receives the message in Figure \ref{fig:locationmessage}. 
The first stage is to extract the desired message from any additional layers, in this case {\tt place/coordinates}. 
This message is then repackaged under the names defined by this component's schema using Algorithm \ref{alg:repack_message}. 
Lines \ref{alg:line:lookup_name_start}--\ref{alg:line:lookup_name_end} find the correct name from the lookup table, returning {\tt null} if it does not exist in the table. 
Lines \ref{alg:line:check_children_start}--\ref{alg:line:check_children_end} then either pack the message content under the new name, if it is a single field, or start a composite item otherwise. 
The loop spanning lines \ref{alg:line:repack_children_start}--\ref{alg:line:repack_children_end} then iterates over each item in the message. 
The name of each item can be used to check if any items are missing from the message, and add them between their siblings. 
The message is otherwise repackaged in the same way, and added to the composite item if it should appear. 
Any other siblings missing from the message can be added at the end. 
Finally, if the component schema had additional layers rather than the peer schema, the message would be wrapped in these missing layers. 
This repackages the message in Figure \ref{fig:locationmessage} to Figure \ref{fig:locationmessagerepack}, which can then be used by the component. 

\begin{algorithm}
\algnotext{EndIf}
\begin{algorithmic}[1]
\Function{RepackageMessage}{$message$}
	\If{$message.name \in lookup\_table$} \label{alg:line:lookup_name_start}
		\State $name\gets \Call{Lookup}{message.name}$
	\Else
		\State \Return $null$
	\EndIf \label{alg:line:lookup_name_end}
	
	\If{$message.children = null$} \label{alg:line:check_children_start}
		\State \Return \Call{Pack}{$message, name$}
	\Else
		\State $composite\gets \Call{CreateStructure}{name}$
	\EndIf \label{alg:line:check_children_end}
		
	\ForAll{$child \in message.children$} \label{alg:line:repack_children_start}
		\State \Call{AddMissingChildren}{$composite$}
		
		\State $node \gets \Call{RepackageMessage}{child}$
		\If{$node \neq null$}
			\State \Call{AddNode}{$composite, node$}
		\EndIf
	\EndFor \label{alg:line:repack_children_end}
	
	\State \Call{AddMissingChildren}{$composite$}

	\State \Return $composite$
	
\EndFunction
\end{algorithmic}
\caption{Pseudocode to Repackage Message}
\label{alg:repack_message}
\end{algorithm}

% repackage messages
\begin{figure}
\begin{lstlisting}[style=xml]
<place>
	<coordinates>
		<position>
			<longitude>0.091732</longitude>
			<latitude>52.210891</latitude>
			<height>19</height>
		</position>
	</coordinates>
	<country>"UK"</country>
</place>
\end{lstlisting}
\caption{Example Location Message}
\label{fig:locationmessage}
\end{figure}

\begin{figure}
\begin{lstlisting}[style=xml]
<location>
	<gps>
		<longitude>0.091732</longitude>
		<latitude>52.210891</latitude>
		<altitude>19</altitude>
	</gps>
	<city>""</city>
</location>
\end{lstlisting}
\caption{Repackaged Location Message}
\label{fig:locationmessagerepack}
\end{figure}

\section{Android Port}

The Android Native Development Kit (NDK) can be used to embed native machine code into applications, and the Java Native Interface (JNI) framework provides a way for applications written in Java to call functions implemented in this native code.
The NDK was used to compile SBUS to support Android, and the JNI framework was used to allow applications for Android to be written in Java, which can use the SBUS middleware. 
The documentation for the NDK offers little more than trivial examples, and few other resources exist, so this stage of the project was largely achieved through experimentation. 

 % overview of Android architecture
\begin{figure}[h]
%set the image x size to the width of the page
\epsfxsize=8cm
\centerline{\epsfbox{figs/android_stack.eps}}
\caption[Android System Architecture]{A brief overview of the Android system architecture, based on the image at \url{http://developer.android.com/images/system-architecture.jpg}}
\label{fig:android_stack}
\end{figure}

% how Android works
Figure \ref{fig:android_stack} gives an overview of how an Android application works. 
Applications are built using the Application Framework. 
Every application runs in its own process, with its own instance of the Dalvik virtual machine\footnote{\url{http://developer.android.com/about/versions/index.html\#os_architecture}}, which executes Java bytecode. 
When an SBUS call is made in Java, Dalvik invokes a call to the native JNI code, passing in a {\tt JNIEnv} pointer containing an interface to the Dalvik VM, as well as any other parameters. 
The JNI methods can then invoke their respective SBUS methods.

% how NDK was done.
A standalone toolchain from the NDK can be used to set the correct compilation variables when running {\tt ./configure}. 
In setting up the toolchain, the architecture of the device and the Android native API platform must be specified. 
ARM-based devices, and Android platform 9 were chosen here, since these corresponded to the available device. 
The standalone toolchain is still in beta which meant there were several problems compiling SBUS directly, typically due to missing libraries. 
Some SBUS code had to be rewritten to account for this, in many cases using {\tt \#ifdef} statements to substitute blocks of code specific to Android. 
The toolchain setup contained a bug\footnote{\url{https://code.google.com/p/android/issues/detail?id=35279}} which meant some include paths were missing, in particular {\tt <limits>} could not be referenced. 
The workaround for this was fixing the directory structure of the toolchain so that the paths were correct. 

The Android version of {\tt pwd.h} which defines {\tt struct passwd} contains no member {\tt pw\_gecos}. 
This contains the user's full name, which is used by SBUS to set the {\tt creator} field in a component's metadata, allowing components to query an RDC by creator. 
To remedy this, the creator was simply replaced by the string ``Android''. 
In principle, the user's full name or username could be found in Java using the AccountManager class\footnote{\url{http://developer.android.com/reference/android/accounts/AccountManager.html}}, which could then be passed as a parameter to the component via JNI. 
This would allow the creator to be set correctly, however it was deemed unimportant to the project. 

% IP address.
One of the greatest problems was that {\tt <sys/sockio.h>} was missing from Android.
SBUS uses this as part of determining the IP address a component is running on, which is then used during connection setup. 
This meant that the entire method to determine the IP address had to be rewritten to work on Android. 
This was achieved by passing an {\tt ifconf} structure to the {\tt ioctl()} system call.
This populates the structure with a list of network interfaces and their IP addresses, which can then be searched for the appropriate interface to find the IP address. 
In this case, the {\tt eth0} interface for Wi-Fi was prioritised over the 3G interface.

% Android FS.
Another large issue was the Android filesystem. 
When creating a component, SBUS invokes a wrapper which is responsible for handling the low level messages between components, passing them to the library level as structured messages.
This typically resides at {\tt /usr/bin/sbuswrapper} which means it can be invoked via a call to {\tt sbuswrapper}, since the {\tt PATH} environment variable contains {\tt /usr/bin}. 
For the same functionality, the wrapper needed to be stored in a directory which is in the {\tt PATH} variable, which on Android, amounts to {\tt /system/bin}. 

The Android SDK provides the Android Debug Bridge ({\tt adb}) which can be used to push and pull files to and from a device. 
When using the Android emulator, {\tt /system} can be remounted as writable\footnote{using {\tt mount -o rw,remount -t yaffs2 /dev/block/mtd3 /system }}, allowing {\tt sbuswrapper} to be pushed to {\tt /system/bin/sbuswrapper}. 
However, on a device without root access, {\tt /system/bin} cannot be remounted in this way, thus cannot be written to. 
Therefore, some other writable directory was needed, and {\tt sbuswrapper} would have to be invoked using the full path. 

The SD card ({\tt /mnt/sdcard}) is writable so was considered, however is mounted with the option {\tt noexec}, which means that although a file can be pushed to it, it cannot be executed. 
The best approach to use was to include {\tt sbuswrapper} as an asset to an application, and copy it to the application's filespace, invoking it from this filespace for every application. 

Android uses a sandbox concept for security, where each application has access only to its own resources on the device. 
This is enforced by assigning each application a unique user ID, and setting the appropriate permissions \cite{enck2009understanding}. 
Since {\tt sbuswrapper} is approximately \SI{1}{MB}, compared to approximately \SI{30}{MB} available internal storage on the device, it was infeasible to include a copy with every application. 
Therefore, one copy was included with the Phone Manager, which then modified the permissions to make {\tt sbuswrapper} world executable, so that every application could use this instance. 
An additional directory was created and made world writable, where SBUS can write log files for all applications. 
If internal storage was not an issue on the device, each application could store its own copy of {\tt sbuswrapper} in its filespace, and log to its own filespace. 
The path to this filespace can be obtained using an Android library call, which could be used as a parameter to a JNI method to set the location of {\tt sbuswrapper}, avoiding hardcoding any paths. 

Although the device could have been rooted, allowing a much cleaner solution of storing {\tt sbuswrapper} at {\tt /system/bin/sbuswrapper}, it would have been less convenient, because the project would only then work on rooted devices. 

%TODO: write about closing sockets and all those FIN_WAIT2? Nothing actually changed now, but it was a pain.

% JNI.
The Android NDK was finally used in conjunction with the Java Native Interface (JNI) framework to allow applications to call SBUS functions via Java. 
This involved writing Java classes for components, endpoints and messages, as well as some helper classes. 
The SBUS library is linked via an {\tt Android.mk} file, which {\tt ndk-build} then uses to copy the shared library into the application's root project directory. 
The application can then be built to generate a package file including SBUS which can run on an Android device. 

Each Java object has a one-to-one correspondence with a native object. 
Native methods which create an object return a pointer to that object, cast as an integer. 
The pointer is passed to the constructor of the Java object representing the native object, to be stored in the Java object. 
When a method is invoked on the Java object, the pointer is passed into the native method, which then casts it to a pointer to the native object, to operate on that object. 
The Java classes hide this complexity from the user, simply providing methods with parameters and return values in terms of these other Java classes.

These classes are exported as a JAR file, which applications can then simply import to use the Java SBUS library.

\section{Phone Manager}

The Phone Manager is an Android application which is responsible for detecting changes in context and reconfiguring other applications' connections. 
The Phone Manager uses the AIRS application\footnote{\url{https://play.google.com/store/apps/details?id=com.airs}} to detect changes in context, however could easily incorporate data from any other source, especially if presented in the form of an SBUS message. 

% AIRS
An application has been created to act as an AIRS-SBUS gateway between AIRS and the Phone Manager, allowing the Phone Manager to use any sensor on the device which is exposed by AIRS. 
The Phone Manager sends messages to an endpoint on the gateway to instruct it to subscribe to particular sensors. 
Upon receiving a message, the gateway subscribes to the appropriate sensor in AIRS. 
AIRS then monitors the relevant sensors, and sends sensor readings to the gateway, which converts them into SBUS messages. 
These messages can then be published to the Phone Manager, or indeed any other application. 
 
 % AIRS-SBUS gateway
This gateway is based on Dirk Trossen's AIRS code\footnote{\url{https://github.com/dirktrossen/AIRS}}. 
AIRS exposes upwards of 50 sensors, which is being continually expanded, making it infeasible to predefine an endpoint for each sensor. 
%The available sensors on a device are announced in a message which AIRS sends when connecting to the gateway. 
Since the sensors which will be subscribed to are initially unknown, endpoints are created dynamically for each sensor as needed. 
When the Phone Manager subscribes to a sensor, via the gateway, an endpoint is created for that sensor as soon as the first reading for that sensor is received from AIRS. 
Additionally, this endpoint is automatically mapped to the Phone Manager so can start publishing events to it immediately. 
Endpoints are maintained in a repository, which is searched upon receiving a sensor reading, to ensure that multiple endpoints are not defined for the same sensor. 

% composite event detector
Conceptually this AIRS-SBUS gateway could act as a composite event detector \cite{chakravarthy1994composite}, or provide the data for some other composite event detector. 
By collating multiple sensor readings, a context change could be defined by multiple different readings satisfying some conditions, or by multiple occurrences of an event.
Upon detecting a context change, a single event would be published to the Phone Manager. 
The Phone Manager can respond to any kind of event, so already provides the infrastructure required to support this.

% registering components + setting policies
In order to have their connections automatically reconfigured, applications must register with the Phone Manager. 
This registration occurs in exactly the same way as with an RDC. 
Once an application has registered, it can set {\sl policies} for its endpoints, which determine how its connection will be reconfigured. 
These policies are event-condition-action rules \cite{mccarthy1989architecture}. 
When an event occurs, if the condition is satisfied by that event, the action is taken. 
A policy contains the type of sensor (event), a condition which that sensor reading must satisfy (condition), and parameters specifying peers which the endpoint should be mapped to (action). 
These parameters include a peer endpoint name and a peer address, in the form of an IP address or an RDC query which will be resolved to an address. 
When a sensor reading occurs, the Phone Manager iterates through all registered policies in order to check whether each policy is interested in the sensor, and whether its conditions are satisfied by the sensor reading. 
For those policies which are satisfied by the sensor reading, the Phone Manager applies the policy action, mapping application endpoints exactly as specified in the policy. 
To do this, it simply issues map events to application endpoints, containing the peer address and peer endpoint name specified in their policies. 
If the peer address specifies an IP address, then the endpoint can map directly to the peer endpoint. 
If the peer address is an RDC query, then the application must first resolve the query against an RDC, then map to the peer endpoint. 

% RDC updates 
Some context changes may mean that the available RDCs change, for example joining or leaving a network. 
The Phone Manager monitors network changes using Android intents\footnote{\url{http://developer.android.com/reference/android/content/Intent.html}}. 
Intents are broadcast across the system to indicate that something has happened, and by implementing a receiver, intents can be captured and an action can be taken. 
An intent with the action {\tt NETWORK\_STATE\_CHANGED\_ACTION} is broadcast upon a network change. 
The Phone Manager registers a receiver for these intents, allowing it take an action after a network change. 
The Phone Manager informs all registered applications of RDC changes on every network context change, publishing an event containing the RDC address, and whether it has became available or unavailable, according to whether the device has left or joined the network. 
Upon receiving the event, applications can automatically accept the change, registering with or deregistering from the RDC address, and can perform a callback method, perhaps prompting the user to make a decision. 


% apply map policies
The Phone Manager sends RDC updates to registered applications before applying any policies. 
This allows RDC queries specified in policies to be resolved against an RDC in the new environment, allowing endpoints to map to peers within that environment. 

% where to get RDC address from
This RDC address is currently set by the user in the Phone Manager, however many other ways exist which could be used to find an RDC in the environment. 
Prompting the user may be sufficient on a home network, and additionally this allows the user to choose not to trust an IP address. 
Alternatively, the address could be coded in a QR code or RFID tag. 
The user could scan one of these, for example when making a purchase in a coffee shop, and the Phone Manager would automatically send an RDC update based on the encoded address. 
This approach retains some level of privacy and security because the user explicitly chooses to scan the QR code or RFID tag. 
An even more automated approach might be for a DHCP server to encode the RDC address in the options of a DHCP Offer message \cite{droms1997dynamic} sent to the device when it connects to a Wi-Fi network. 
Alternatively, the RDC address might be broadcast on the network. 
All of these methods must of course be considered from security point of view. 

\section{Issues}
% remaining problems
The system currently faces issues when context is rapidly changing, for example, moving in and out of range of a Wi-Fi network. 
The network connection drops causing the Phone Manager to reconfigure connections, which may disconnect applications from their peers.
However, the network connection is almost immediately re-established causing the Phone Manager to reconfigure connections again, possibly connecting applications to these same peers. 
If this reconnection occurs before disconnection has completed, an application believes itself to still be connected to the peer, thus will not create a new connection.

While this problem might be solved by using a condition which requires the network signal to be greater than a given threshold, meaning reconfiguration would not occur until the user moves firmly into the network, an alternative solution might use a composite event detector. 
A composite event detector would trigger events after multiple occurrences of a single event, so that reconfiguration is not performed as frequently. 
For example, a single event could be triggered after three consecutive Wi-Fi events have occurred with increasing signal strength. 

% qualify names if multiple fields in sensor have same name
Components specify RDC schema queries in terms of field names of their own schema.
While this is sufficient if there are no repeated fields names within the schema, it may have unexpected results on a schema such as Figure \ref{fig:repeatednameschema} due to the ambiguity in the {\tt sensor} field name. 
A solution to this would be to force field names to be fully qualified in a query. 
A query using {\tt sensor} would refer to the entire structure, while {\tt sensor/sensor} would refer to the text field.

\begin{figure}[h]
\begin{lstlisting}
@sensor
{
	txt sensor
	int value
}
\end{lstlisting}
\caption[Ambiguously Named Schema]{A schema with a structure named {\tt sensor} and a text field also named {\tt sensor}. A constraint specified on {\tt sensor} would be ambiguous without fully qualified names}
\label{fig:repeatednameschema}
\end{figure}


\cleardoublepage


% ~ Eval + Conclusion ~ 2000 words
\chapter{Evaluation}

The project set out to investigate how applications could automatically connect to different peers upon a change in context, where these peers may not necessarily present data in the format expected. 
The project has been successful in this respect, implementing a system which gives applications these capabilities.  
Sensor readings from the AIRS application\footnote{\url{https://play.google.com/store/apps/details?id=com.airs}} and Android intents are used to detect a change in context. 
Once a change is detected, applications will be connected to peers which satisfy the constraints they have specified and messages will automatically be converted to applications' expected format, allowing operation of the application to continue without interruption. 
This chapter demonstrates the feasibility of the approach, and examines its performance. 

\section{System Overview}

% overview of system image
\begin{figure}[t]
%set the image x size to the width of the page
\epsfxsize=\hsize
\centerline{\epsfbox{figs/overview.eps}}
\caption[System Overview]{An overview of the system, showing interactions between different parts upon a context change}
\label{fig:system_overview}
\end{figure}

Figure \ref{fig:system_overview} shows the interactions that occur within the system. 
These steps detail how a transport application might have its connection reconfigured upon a change in context. 

\begin{enumerate}

\item The transport application has registered with the Phone Manager, and sets a policy specifying that whenever the Wi-Fi SSID changes to ``National\_Express'', indicating that the user is using a Wi-Fi network in a coach station, it should be connected to any component named ``Coach'' (using the query string {\tt +Ncoach}).   

\item The Phone Manager sends a message to the AIRS-SBUS gateway to subscribe to Wi-Fi SSID sensor readings. The gateway then subscribes to these sensor readings from AIRS. 

\item The AIRS-SBUS gateway sends an SBUS event to the Phone Manager whenever a sensor reading is received from AIRS, which is then checked against the policy table. The Phone Manager also receives intents from the Android system which signal a network change. 

\item The user walks in to the coach station, and connects to the Wi-Fi network. The Phone Manager receives an intent indicating that the device has connected to the Wi-Fi network, and informs the transport application of an RDC in the network. 

\item The transport application receives the RDC update, and automatically registers with the RDC. It additionally performs a callback method, simply displaying a message that a new RDC has been added. 

\item The Phone Manager receives an event from the gateway which indicates that the Wi-Fi SSID is now ``National\_Express''. It applies the transport application's policy, instructing its endpoint to map using the query string {\tt +Ncoach}.

\item The endpoint must first resolve this query, so sends the query to all RDCs which it is registered with. 

\item RDCs resolve this query, returning a list of addresses of registered components which match the query. An RDC returns a matching component on the Wi-Fi network. 

\item The endpoint connects to this matching component, allowing the user to continue receiving fresh travel data without any interaction needed.

\end{enumerate}

% about example policies
The system is in line with an event-condition-action model, using sensor readings (events) to map application endpoints (actions) whenever the sensor readings satisfy some conditions (conditions). 
Table \ref{tab:example_policies_eca} shows example policies which components might set with the Phone Manager. 
Both the local component and local endpoint are implicitly set to whichever endpoint sent the policy, and are not shown here. 
The remote address may be an IP address or a query to be resolved by an RDC. 
An IP address may be useful when the application should always be mapped to the same IP address, however queries allow applications to be more flexible in their peers. 
Queries will be resolved by some RDC, ensuring components are mapped only to other components which satisfy their queries. 
 
\begin{table}
\centering

\newcounter{row}
\newcommand\rownumber{\refstepcounter{row}\arabic{row}:}

\begin{tabular}{l c c c c}
\hline\hline
& Event & Condition & \multicolumn{2}{c}{Action} \\
&&& Address & Endpoint \\
\hline

\rownumber\label{tab:row:heart} 			&	Accelerometer 	& val $\ge50$ 				& 128.232.0.20:44444 	& HeartRate \\
\rownumber\label{tab:row:advert}			&	Time			& val.hour = 12 			& +IRestaurant			& Advert \\
\rownumber\label{tab:row:transport:wifi} 	&	Wi-Fi 			& val = true 				& +NStagecoach 			& Coach \\
\rownumber\label{tab:row:transport:gps} 	&	GPS 			& location(val) = France 	& +Scoach 				& NULL \\
\rownumber\label{tab:row:gps} 				&	GPS				& NONE						& +IAdvert				& NULL \\
\rownumber\label{tab:row:none} 				&	NONE			& NONE						& localhost:44444			& NULL \\

\hline
\end{tabular}

\caption{Phone Manager Example Policies}
\label{tab:example_policies_eca}
\end{table}

In row \ref{tab:row:heart}, a healthcare system has registered to have heart rate readings mapped directly to an endpoint at a known IP address, perhaps a relative or emergency response team. 
This will only take place if a high accelerometer value was measured, because the reading may indicate that a fall has occurred.  
In row \ref{tab:row:advert}, an application may display adverts from nearby restaurants if it is around lunchtime. 
In row \ref{tab:row:transport:wifi}, the transport application wants to connect specifically to a Stagecoach component with an endpoint named ``Coach'' if a Wi-Fi connection is established. 
However, as per row \ref{tab:row:transport:gps}, if a GPS event indicates that the user is in France, the application is more lenient and willing to connect to any component with an endpoint offering a structure matching the type of {\tt coach}. 
Row \ref{tab:row:gps} shows a policy which specifies an event, but no condition. 
This is perfectly acceptable, and the action will occur on every GPS event. 
In this case an application will attempt to connect to any endpoint offering adverts. 
Finally, row \ref{tab:row:none} shows a ``blank'' policy, with no event or condition specified.  
This policy will be applied on any event, however this attempts to connect to an address without any endpoint specified, so no connection is made. 

% user policies
While applications can only set policies for themselves, this could be extended to allow the user to set their own policies for applications. 
The application developer cannot possibly account for every scenario, however by allowing the user to set their own policies, through which they are specifying context changes they are interested in, the system becomes fully customisable and personal. 
The user of the transport application might not want to wait for a bus when it is raining. 
Therefore, they could create a policy using a weather event with the condition ``rain''. 
The action might be to connect the application to the IP address of a local taxi company, which provides information about when the next taxi will be available using the schema in Figure \ref{fig:taxi-schema-eval}.

\begin{figure}
\input{schema.taxi}
\caption[Example Schema for a Taxi]{A taxi schema, simply showing the next available taxi}
\label{fig:taxi-schema-eval}
\end{figure}

%TODO: UI for user to set policy (system can also set policy).

%TODO: Screenshots of original message + repackaged?

%TODO: How long to go through policy list (all the if statements)

%TODO: How long to tell a component about context change - long list, might take a while for last one - prioritise?

\section{System Performance}

This section examines the performance of the system, specifically aspects related to schema conversion and connection reconfiguration.  
The schema conversion plays an important role in mobility because it allows applications to function despite some level of uncertainty, which in turn makes them more adaptable to different environments. 
Both the schema conversion and connection reconfiguration are only useful if they can be done in reasonable time, since the whole idea behind the system is to provide users with meaningful, {\sl real time} data. 
These tests show the kind of performance which can be expected from the system. 

% time to apply policies
\begin{figure}
\epsfxsize=\hsize
\centerline{\epsfbox{figs/policy.eps}}
\caption{Time Taken to Compare Sensor Reading Event to Policies}
\label{fig:policy_times}
\end{figure}

Figure \ref{fig:policy_times} shows the time taken between receiving an event from the AIRS-SBUS gateway and comparing the event to all registered policies, for different numbers of policies. 
After ten policies, the relationship between number of policies and time taken to check these policies is near linear. 
The upper bound for the time which can be spent servicing policies is determined by the frequency with which AIRS outputs sensor readings. 
If the Phone Manager is receiving events faster than it can compare the events against all policies, then a more efficient data structure would be required to store the policies. 
For example, policies could be indexed by sensor type, rather than stored in one list, as they are now. 
However, the current implementation, which can check 1000 policies in approximately \SI{65}{\milli\second} could support up to 15 sensors being sampled each second. 

% rdc search optimisation
\begin{figure}
\epsfxsize=\hsize
\centerline{\epsfbox{figs/rdc_search_optimisations.eps}}
\caption{RDC Search Optimisations}
\label{fig:rdc_search_optimisations}
\end{figure}

Figure \ref{fig:rdc_search_optimisations} shows the time taken for an RDC to search through all registered components to find those matching schema constraints, for different numbers of registered components and with different optimisations applied. 
In a real environment, RDCs are likely to have many components registered, so one search must not impact the performance of any other component too greatly.
As expected, the time taken to search increases linearly with the number of components registered. 
The structures first optimisation narrowly beats the exact first and exact structures optimisations, all of which perform more efficiently than searching without optimisation. 
These optimisations play a greater role as the number of components increases, becoming more important in order to prevent a bottleneck in the system. 
While not making a lot of difference here, this only demonstrates one query. 
In a real world use of the system there may be far more complex queries performed, in which case the optimisations may offer a greater performance increase.  

% construct lookup
\begin{figure}
%\epsfxsize=\hsize
\centerline{\epsfbox{figs/construct_lookup.eps}}
\caption[Construct Lookup Times]{Time taken ($\mu$s) to construct a lookup table between schemas of different sized producers and schemas of different sized consumers}
\label{fig:construct_lookup}
\end{figure}

Figure \ref{fig:construct_lookup} shows the time taken to construct a lookup table between schemas of different sized producers and schemas of different sized consumers. 
The lookup table is created before any messages can be exchanged between peers with different schemas, to allow messages to be repackaged to fit the consumer's schema. 
The general increase in time from left to right shows that more time is taken to construct a lookup table as the size of the producer schema increases, as expected, since there are more fields. 
The greater values in the upper right half of the graph show a disparity with the smaller values in the lower left half of the graph. 
This shows that the time taken to construct a lookup table is greater when the producer's schema is larger than the consumer's schema, corresponding to searching in the larger producer schema for the smaller consumer schema to be matched, as opposed to identifying the missing outer structures if the consumer schema were larger.
In either case, the lookup table is constructed once per connection taking only microseconds, so is not a significant overhead. 

% repack message
\begin{figure}
%\epsfxsize=\hsize
\centerline{\epsfbox{figs/repack_message.eps}}
\caption[Repackage Message]{Time taken ($\mu$s) to repackage a message between schemas of different sized producers and schemas of different sized consumers}
\label{fig:repack_message}
\end{figure}

Figure \ref{fig:repack_message} shows the time taken to repackage a message between schemas of different sized producers and schemas of different sized consumers. 
This repackaging happens once per message, thus will cause a delay on every single message received. 
The general increase in time from top to bottom shows that more time is taken when the consumer schema is larger, as expected because more fields are being repackaged under the appropriate names. 
As with constructing the lookup table, messages are repackaged within microseconds, which is an insignificant overhead. 
In general, messages should still be relevant after the time taken for repackaging, for any realistic use of the system.

Both Figure \ref{fig:construct_lookup} and Figure \ref{fig:repack_message} use a schema constraint which matches the type of the smallest schema, to ensure that a match is made in every case. 
These schemas are shown in Appendix \ref{appendix:schemas}. 

\section{Android Port}

This section evaluates the performance of using SBUS on a phone in comparison to using SBUS on a laptop, investigating whether any significant gains or losses occur as a result of using the Android operating system. 

% figure showing map times
\begin{figure}[t]
\epsfxsize=\hsize
\centerline{\epsfbox{figs/map.eps}}
\caption{Connection Times for Producers on Different Devices}
\label{fig:map_times}
\end{figure}

Figure \ref{fig:map_times} and Table \ref{tab:map_times} show mean times and standard deviations for producers running on a phone, a remote machine, and the local machine to connect to a consumer. 

% table showing map times
\begin{table}[h]
\centering

\begin{tabular}{c c c}
\hline\hline

Producer & Mean (ms) & Standard Deviation (ms) \\
\hline

Local Machine	&	1.0268	&	0.5475 \\
Remote Machine	&	16.1411	&	9.3361 \\
Remote Phone	&	15.9605	&	2.6539 \\

\hline
\end{tabular}

\caption{Connection Times for Producers on Different Devices}
\label{tab:map_times}
\end{table}

Each producer first queries an RDC running on the same machine as the consumer, to find the consumer. 
Once the producer receives the IP of the consumer from the RDC, it then establishes the connection with it, hence two connections occur within each mapping. 
No schema conversion occurs as part of this map. 
These figures show that a far greater time is required when the producer is on a different device to the consumer. 
This bears no surprise that local connections are faster than network connections. 
The mean time taken when the producer is on a remote phone is slightly less than when the producer is on a remote machine, though the standard deviation is significantly less. 
Overall, an application written in Java running a phone would see very similar network delays to that of a program written in C++ running on any other machine.


Figure \ref{fig:jni_times} shows the breakdown of time taken to perform an SBUS function call via Java compared to C++. 
In this case, the function call is to emit a message. 
This shows that the function call in C++ takes slightly over one millisecond, while using Java to call the native method via JNI takes almost six milliseconds, almost a five millisecond delay. 
Each call to an SBUS function via Java will incur some delay, meaning that applications written in Java for a phone will never operate as quickly as those written in C++.
Application developers can expect this delay, which is likely to show less variance than any network delay, and can build their applications to take account of it. 
This delay is unlikely to cause a significant problem for most applications. 
An application requiring high performance guarantees would be expected to use custom hardware and software, or to develop the application in native code. 

% figure showing jni times
\begin{figure}
\epsfxsize=\hsize
\centerline{\epsfbox{figs/jni.eps}}
\caption{Function Call via JNI Timing Breakdown}
\label{fig:jni_times}
\end{figure}

%TODO: JNI times for other method calls?

%TODO: Stress test? How many components on Android can communicate?

%TODO: Example code for Android SBUS component?

%TODO: Screenshots?

\cleardoublepage

\chapter{Conclusion}

% summarise
The project has created a context-aware middleware which allows developers to focus on functionality when writing applications, rather than on specific details of which peers the application will use, or how peers might format their data. 
This is in line with the goals of pervasive computing, achieving scalability by allowing applications to use any relevant peer, and allowing applications to adapt to use heterogeneous content, all while being invisible to both the user and developer.

Applications can monitor the environment for events which the system or user believe to represent a change in context.
Upon detection of an event, these applications can apply other applications' reconfiguration policies to connect them to different peers. 
Through these policies, applications can control which peers they should be connected to in each context change, without requiring the applications to find the peers themselves.
Peer constraints may be simple, such as the name of a peer, or more complex, specifying how fields in a peer's schema must match their own. 

Data is reformatted so that applications will only ever be presented with data which conforms to their own format, removing uncertainty about the data representation. 
Furthermore, applications may specify subscription filters in terms of their own data format, placing restrictions on the data they will be sent, without requiring knowledge of peers' data format.
When reconfiguring a connection, the system translates these filters to match the peer's data format and applies them to the peer, filtering data as dictated by the application.

\section{Changes}
%TODO: changes
With the benefit of hindsight, there are no substantial changes to the project which might have made the Implementation smoother than it already was. 

\section{Future Work}
% other stuff that could be done

% multiple conditions in policies
Policies specified by applications can only contain one type of context change, and one condition which that change must satisfy. 
This might be extended to allow multiple conditions within a policy, combined using first order logic statements \cite{ranganathan2003middleware}. 
An application could then specify a conjunction of conditions which must be true, or a disjunction of conditions, one of which must be true before applying this policy. 
Multiple types of context change might also be accepted, allowing complex scenarios to be defined. 

% user defined policies
Applications can currently only specify policies for their own endpoints. 
The system could easily be extended to allow applications to specify policies for {\sl other} applications, subject to any security restrictions, which would allow the user to set custom policies for each application. 
Applications would aim to provide sensible policies for different changes in context, however the user could refine how applications should react by setting their own policies, causing the applications to behave in a way more suited to the user's needs. 
This would require some ``policy authoring'' application, which provides a simple interface to allow the user to set policies for any application on the device. 
This moves further towards the pervasive vision, providing invisibility \cite{saha2003pervasive} in the system by requiring minimal user intervention, yet allowing the user to fine tune settings so that the system can meet more of the user's expectations. 

% user security policies
In addition to the user setting custom policies, the user might also be able define security policies for different applications, which state whether or not an application can use part of their context. 
This offers some privacy to the user by allowing them to block applications from using some part of their context. 
For example, an application may register a policy which uses the user's location. 
Since the application would have a connection reconfigured whenever the user's location changed, it could monitor this, and begin to infer patterns in how the user's context changes. 
The user may decide that they do not wish for this application to be able to use their location, and thus set a security policy which blocks the application from using this particular part of their context. 

\cleardoublepage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the bibliography

\addcontentsline{toc}{chapter}{Bibliography}
\bibliographystyle{ieeetr}
\bibliography{refs}
\cleardoublepage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% the appendices
\begin{appendix}

\chapter{Example Schemas}
\label{appendix:schemas}

These are the example schemas used in part of the Evaluation. 

\input{schemas.evaluation}

\cleardoublepage

\chapter{Project Proposal}

\input{propbody}

\end{appendix}

\end{document}
